package com.syq.service.impl;

import com.google.common.cache.LoadingCache;
import com.syq.cache.SceneCache;
import com.syq.constants.ResultCode;
import com.syq.dao.SysSceneMapper;
import com.syq.exceptions.AddException;
import com.syq.pojo.CheckType;
import com.syq.pojo.SysScene;
import com.syq.pojo.SysUserInfo;
import com.syq.service.SysSceneService;
import com.syq.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.List;

@Service
public class SysSceneServiceImpl implements SysSceneService {
    private SysSceneMapper sceneMapper;

    private SceneCache sceneCache;

    @Autowired
    public void setSceneCache(SceneCache sceneCache) {
        this.sceneCache = sceneCache;
    }

    @Autowired
    public void setSceneMapper(SysSceneMapper sceneMapper) {
        this.sceneMapper = sceneMapper;
    }

    @Override
    public void addScene(SysScene sysScene) {
        Assert.isTrue(!sysScene.isEmpty(CheckType.ADD),()->{
            throw new AddException("请输入完整数据", ResultCode.DATA_NULL);
        });
        SysUserInfo userinfo = SecurityUtils.getUserinfo(false);
        SysScene byUserIdAndSceneName = sceneMapper.findByUserIdAndSceneName(userinfo.getUId(), sysScene.getSceneName());
        Assert.isNull(byUserIdAndSceneName,()->{
            throw new AddException("场景已存在",ResultCode.DATA_ALREADY_EXIST);
        });
        sysScene.setCreateBy(userinfo.getUId());
        sceneMapper.addScene(sysScene);
    }

    @Override
    public List<SysScene> findAllSceneByUserId() {
        SysUserInfo userinfo = SecurityUtils.getUserinfo(false);
        List<SysScene> userScenelist = sceneCache.getUserScene().getUnchecked(userinfo.getUId());
        return userScenelist;
    }
}
